package teaching.controller.textBookManage.textBookOrder;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import teaching.entity.TextBookOrder;
import teaching.service.baseInfoManage.common.BaseInfoCommonService;
import teaching.service.baseInfoManage.common.ExcelUtil;
import teaching.service.textBookManage.textBookOrder.TextBookOrderService;

@Controller
@RequestMapping(value="textBookOrder")
public class TextBookOrderController {
  
	@Autowired
	private TextBookOrderService textBookOrderService;
	@Autowired
	private BaseInfoCommonService baseInfoCommonService;
	
	/**
	 *  查询订单map(page,pageSize,majorName,academicYear,term,grade)
	 * @author GuoFei
	 * @param page
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="getTextBookOrder")
	 @ResponseBody
	public Map<String, Object> getTextBookOrder(@RequestParam(value="page",required=false) Integer  page,@RequestParam(value="pageSize",required=false) Integer  pageSize,HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String, Object>();
		Map<String,Object> map2 = new HashMap<String, Object>();
		int start = 0; 
		 if(page!=null&&pageSize!=null){
			 start = (page-1)*pageSize;
		 }
		map.put("start",start);
		map.put("pageSize",pageSize);
		map.put("majorName", request.getParameter("majorName"));
		map.put("majorId", request.getParameter("majorId"));
		map.put("academicYear", request.getParameter("academicYear"));
		map.put("term", request.getParameter("term"));
		map.put("grade", request.getParameter("grade"));
		map.put("createTime", request.getParameter("createTime"));
		map.put("isConfirm", request.getParameter("isConfirm"));
		map.put("orderID", request.getParameter("orderID"));
		List<Map<String,Object>> list = null;
		try {
			list = textBookOrderService.getTextBookOrder(map);
			int countNum = textBookOrderService.getOrderCountNum(map);
			System.out.println("list.size()"+list.size());
			if(list!=null&&list.size()>0){
				map2.put("orderList", list);
				map2.put("countNum", countNum);
			}else{
				Map<String,Object> map3 = new HashMap<String, Object>();
				map3.put("start",start);
				map3.put("pageSize",pageSize);
				map3.put("pageSize",pageSize);
				map3.put("teacherId","");
				
				List<Map<String,Object>> obj = textBookOrderService.getArrangeCourse(map3);
				for(Map<String,Object> o :obj){
					o.put("publishingHouse", "");
					o.put("isbn", "");
					o.put("textbookName", "");
					o.put("author", "");
					o.put("price", "");
					o.put("orderID", "");
					o.put("classId", "");
					o.put("className", "");
					o.put("majorName", "");
					o.put("majorId", "");
					o.put("orderNum", "");
					o.put("isConfirm", "");
					o.put("teacherId", "");
					o.put("textbookId", "");
					o.put("remark1", "");
				}
				map2.put("orderList", obj);
				map2.put("countNum", textBookOrderService.getCountCourse(map3));
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map2;
		
	}
	
	/**
	 *  查询订单map(page,pageSize,majorName,academicYear,term,grade)
	 * @author GuoFei
	 * @param page
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="getTextBookOrder2")
	 @ResponseBody
	public Map<String, Object> getTextBookOrder2(@RequestParam(value="page",required=false) Integer  page,@RequestParam(value="pageSize",required=false) Integer  pageSize,HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String, Object>();
		Map<String,Object> map2 = new HashMap<String, Object>();
		int start = 0; 
		 if(page!=null&&pageSize!=null){
			 start = (page-1)*pageSize;
		 }
		map.put("start",start);
		map.put("pageSize",pageSize);
		map.put("majorName", request.getParameter("majorName"));
		map.put("majorId", request.getParameter("majorId"));
		map.put("academicYear", request.getParameter("academicYear"));
		map.put("term", request.getParameter("term"));
		map.put("grade", request.getParameter("grade"));
		map.put("createTime", request.getParameter("createTime"));
		map.put("isConfirm", request.getParameter("isConfirm"));
		map.put("orderID", request.getParameter("orderID"));
		List<Map<String,Object>> list = null;
		try {
			list = textBookOrderService.getTextBookOrder(map);
			int countNum = textBookOrderService.getOrderCountNum(map);
			System.out.println("list.size()"+list.size());
			if(list!=null&&list.size()>0){
				map2.put("orderList", list);
				map2.put("countNum", countNum);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map2;
		
	}
	
	/**
	 * 新增订单TextBookOrder
	 * @author GuoFei
	 * @param request
	 * @param response
	 * @return
	 * @throws ParseException 
	 * 
	 */
	@RequestMapping(value="addTextBookOrder")
	 @ResponseBody
	public Map<String,Object> addTextBookOrder(@RequestBody Map<Object, Object> order,
			HttpServletRequest request,HttpServletResponse response) throws ParseException {
		
	
		
		Map<String,Object> resultMap = new HashMap<String, Object>();
		String academicYear = (String) order.get("academicYear");
		String term = (String) order.get("term");
		String grade = (String) order.get("grade");
		List<TextBookOrder> list = new ArrayList<TextBookOrder>();
		List<String> classIdList = new ArrayList<String>();
	    List<Map<String,Object>> orderList = (List<Map<String, Object>>) order.get("order");
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(orderList!=null){
			
			for(int i = 0;i<orderList.size();i++){
				Map<String,Object> obj =  orderList.get(i);	
				String classId =  (String) obj.get("classId");
				classIdList.add(classId);
				String textbookId = (String) obj.get("textbookId");
				
	
				String courseId = (String) obj.get("courseId");
				String majorId = (String) obj.get("majorId");
				//新增教材订单信息
				TextBookOrder textBookOrder = new TextBookOrder();
				textBookOrder.setOrderID(UUID.randomUUID().toString().replaceAll("-", ""));	
				textBookOrder.setCourseId(courseId);
				textBookOrder.setTextbookId(textbookId);
				String orderNum2 = obj.get("orderNum").toString();
				if(!"".equals(orderNum2)&&orderNum2!=null){
					textBookOrder.setOrderNum(Integer.parseInt(orderNum2));
				}
				
				textBookOrder.setTerm(term);  
                textBookOrder.setAcademicYear(academicYear);
							
				textBookOrder.setGrade(grade);			
				textBookOrder.setCreateTime(sdf.parse(sdf.format(new Date())));
				textBookOrder.setMajorId(majorId);
				textBookOrder.setIsConfirm("0");
				textBookOrder.setRemark1((String) obj.get("remark1"));
				if(textBookOrder.getTextbookId()!=null&&!"".endsWith(textBookOrder.getTextbookId())){
				  list.add(textBookOrder);
				}
				
				
			}
			
			try {
				textBookOrderService.addTextBookOrder(list);
				//添加班级-订单信息
				List<Map<String,Object>> classToOrder = new ArrayList<Map<String,Object>>();
				int j = 0;
				for(TextBookOrder  textBookOrder :list){				
					Map<String,Object> map2 = new HashMap<String, Object>();
								
					if(classIdList.get(j)!=null){
						map2.put("orderId", textBookOrder.getOrderID());
						map2.put("classId", classIdList.get(j));
						classToOrder.add(map2);
					}
					
					j++;
				}	
				if(classToOrder!=null){
					textBookOrderService.addOrderAndClass(classToOrder);
				}
				
				resultMap.put("message", "添加订单成功");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				resultMap.put("message", "添加订单失败");
				e.printStackTrace();
			}
		}
			
		return resultMap;
		
	}
	/**
	 * 修改订单
	 * @param request
	 * @param response
	 * @return
	 * @throws SQLException 
	 * @throws ParseException 
	 */
	@RequestMapping(value="updateOrder")
	 @ResponseBody
	public Map<String,Object> updateOrder(@RequestBody Map<Object, Object> order,HttpServletRequest request,HttpServletResponse response) throws SQLException, ParseException{
		Map<String,Object> resultMap = new HashMap<String, Object>();
		//String order =  request.getParameter("order");
		
		List<String> classIdList = new ArrayList<String>();
		List<Map<String,Object>> orderList = (List<Map<String, Object>>) order.get("order");
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(orderList!=null){
			List<TextBookOrder> list = new ArrayList<TextBookOrder>();
			//for(int i = 0;i<orderList.size();i++){
				Map<String,Object> obj =  orderList.get(0);	
				String classId =  (String) obj.get("classId");
				classIdList.add(classId);
				
				
				//String academicYear = (String) obj.get("academicYear");
				//确认教材订单信息
				TextBookOrder textBookOrder = new TextBookOrder();
				
				textBookOrder.setOrderID((String) obj.get("orderID"));
				textBookOrder.setCourseId(obj.get("courseId").toString());
				textBookOrder.setTextbookId(obj.get("textbookId").toString());
				textBookOrder.setOrderNum(Integer.parseInt(obj.get("orderNum").toString()));
				//textBookOrder.setTerm((String) obj.get("term"));			
				//textBookOrder.setAcademicYear(academicYear );
				//textBookOrder.setGrade((String) obj.get("grade"));
				//textBookOrder.setCreateTime(new Date().toString());
				textBookOrder.setTeacherId((String) obj.get("teacherId"));
//				textBookOrder.setIsConfirm("1");
				textBookOrder.setRemark1((String) obj.get("remark1"));
			
				
			//}
			try {
				
				textBookOrderService.updateOrder2(textBookOrder);
				//修改班级-订单信息
				List<Map<String,Object>> classToOrder = new ArrayList<Map<String,Object>>();
				int j = 0;
			
					
					Map<String,Object> map2 = new HashMap<String, Object>();
					map2.put("orderID", textBookOrder.getOrderID());
					map2.put("classId", classId);
					
		
				textBookOrderService.updateOrderAndClass2(map2);
				
				resultMap.put("message", "修改订单成功");
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				resultMap.put("message", "修改订单失败");
				e.printStackTrace();
			}
		}
		return resultMap;
	}
	
	/**
	 * 教师确认订单更改状态码为1
	 * 根据当前登陆人将teacherId设值
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="updateIsConfirm")
	 @ResponseBody
	public Map<String,Object> updateIsConfirm(@RequestBody Map<Object, Object> order,HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String, Object>();
		//String orderId =  request.getParameter("orderId");
		List<Map<String,Object>> orderId = (List<Map<String, Object>>) order.get("order");
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
	    HttpSession session = request.getSession();
	    String currentId = "";
		  if(session!=null){
			  currentId = (String) session.getAttribute("id"); 
		  }
		  
		
		if(orderId!=null&&!"".equals(orderId)){
			
			for(int i = 0;i<orderId.size();i++){
				String  id = (String) orderId.get(i).get("orderID");			
				Map<String,Object> map2 = new HashMap<String, Object>();				
				map2.put("orderID", id);
				map2.put("isConfirm", "1");
				map2.put("teacherId", currentId);
				
				list.add(map2);
			}
		}
		try {			
			textBookOrderService.updateOrderByJW(list);
			map.put("message", "确认订单成功");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			map.put("message", "确认订单失败");
			e.printStackTrace();
		}
		
		return map;
	}
	
	
	/**
	 * 教务处提交订单更改状态码为2
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="updateOrderByJW")
	 @ResponseBody
	public Map<String,Object> updateOrderByJW(@RequestBody Map<Object, Object> order,HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String, Object>();
		//String orderId =  request.getParameter("orderId");
		List<Map<String,Object>> orderId = (List<Map<String, Object>>) order.get("order");
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
	    HttpSession session = request.getSession();
	    String currentId = "";
		  if(session!=null){
			  currentId = (String) session.getAttribute("id"); 
		  }
		  
		
		if(orderId!=null&&!"".equals(orderId)){
			
			for(int i = 0;i<orderId.size();i++){
				String  id = (String) orderId.get(i).get("orderID");			
				Map<String,Object> map2 = new HashMap<String, Object>();				
				map2.put("orderID", id);
				map2.put("isConfirm", "2");
				map2.put("teacherId", currentId);
				
				list.add(map2);
			}
		}
		try {			
			textBookOrderService.updateOrderByJW(list);
			map.put("message", "提交订单成功");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			map.put("message", "提交订单失败");
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	  * 导出订单
	  * @param response
	  * @param request
	  * @return
	 * @throws IOException 
	 * @throws FileNotFoundException 
	  */
	 @RequestMapping(value="exportOrder")
	 @ResponseBody
	 public Map<String,Object> exportOrder(HttpServletRequest request) throws FileNotFoundException, IOException{
		  
		    Map<String,Object> map = new HashMap<String, Object>(); 	    
			String basePath = this.getClass().getResource("/").getPath();
			if(System.getProperty("os.name").toLowerCase().indexOf("linux")>=0){
				basePath = basePath.substring(0, basePath.indexOf("/WEB-INF"));
			}else{
				basePath = basePath.substring(1, basePath.indexOf("/WEB-INF"));
			}
			
			String fileName = "template_order.xls";		
			String templatePath = basePath + "/template/textBookOrder/" + fileName;
			// 先读取模板 
		    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(templatePath));
		    HSSFWorkbook wb = new HSSFWorkbook(fs);  
		    //在webbook中添加一个sheet,对应Excel文件中的sheet  
		    HSSFSheet sheet = wb.getSheetAt(0);  
		    //在sheet中添加表头第0行 
		    HSSFRow row;
		    HSSFCellStyle cellStyle = ExcelUtil.setCellStyle(wb);
		    //写入实体数据 ,数据从数据库得到，  
		    List< Map<String,Object>> list = null;
		    Map<String,Object> map2 = new HashMap<String, Object>();	  
			map2.put("majorName",request.getParameter("majorName"));
			map2.put("grade",request.getParameter("grade"));
			map2.put("academicYear", request.getParameter("academicYear"));
			map2.put("term", request.getParameter("term"));
			map2.put("isConfirm", request.getParameter("isConfirm"));
			map2.put("majorId", request.getParameter("majorId"));
			
		    try {
				list = textBookOrderService.getTextBookOrder(map2);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		    
		    if(list!=null){
		    	for (int i = 0; i < list.size(); i++) {
		    		 row = sheet.createRow( i + 1); 		    				                
		            row.createCell(0).setCellValue(list.get(i).get("publishingHouse").toString()); 
		            row.getCell(0).setCellStyle(cellStyle);
		            row.createCell(1).setCellValue(list.get(i).get("textbookName").toString()); 
		            row.getCell(1).setCellStyle(cellStyle);
		            row.createCell(2).setCellValue(list.get(i).get("author").toString());
		            row.getCell(2).setCellStyle(cellStyle);
		            row.createCell(3).setCellValue(list.get(i).get("price").toString()); 
		            row.getCell(3).setCellStyle(cellStyle);
		            row.createCell(4).setCellValue(list.get(i).get("orderID").toString()); 
		            row.getCell(4).setCellStyle(cellStyle);
		            row.createCell(5).setCellValue(list.get(i).get("courseNameCN").toString()); 
		            row.getCell(5).setCellStyle(cellStyle);
		            row.createCell(6).setCellValue(list.get(i).get("className").toString()); 
		            row.getCell(6).setCellStyle(cellStyle);
		            row.createCell(7).setCellValue(list.get(i).get("orderNum").toString()); 
		            row.getCell(7).setCellStyle(cellStyle);
		            row.createCell(8).setCellValue(list.get(i).get("remark1").toString()); 
		            row.getCell(8).setCellStyle(cellStyle);
		          
		        
			                  		     	     
			    }  
		    }
		  
		    
	    try{  
	    	String path = "file/export";
	    	String realPath = request.getSession().getServletContext().getRealPath("/"+path);
	    	String pathtrue = realPath + "/"+fileName;
	        FileOutputStream fout = new FileOutputStream(pathtrue);  
	        wb.write(fout);  
	        fout.close();  
	        String uri =  request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
	       
	        map.put("message", uri+"/"+"TeachingMIS/"+path+"/"+fileName);
	    }  
	    catch (Exception e){ 
	    
	    	map.put("message", "导出失败！");
	        e.printStackTrace();  
	    }  
		 
		 return map;
	 }
	/**
	 * 教材名称及其id
	 * @param request
	 * @return
	 */
	 @RequestMapping("getCourseNameAndId")
	 @ResponseBody
	 public List<Map<String,Object>> getCourseNameAndId(HttpServletRequest request){
		 List<Map<String,Object>> list = null;
		 try {
			list = textBookOrderService.getCourseNameAndId();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return list;
	 }
	 
	 /**
	  * 删除订单
	  * @param request
	  * @return
	  */
	 @RequestMapping("delOrder")
	 @ResponseBody
	 public Map<String,Object> delOrder(HttpServletRequest request){
		 Map<String,Object> map = new HashMap<String, Object>();
		 String orderId = request.getParameter("orderId");
		 try {
			textBookOrderService.delOrder(orderId);
			map.put("message", "删除订单成功！");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			map.put("message", "删除订单失败！");
			e.printStackTrace();
		}
		 return map;
	 }
	 
	 
}
